package com.atguigu.champter8;

import com.atguigu.beans.OrderEvent;
import com.atguigu.utils.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

public class Flink07_Project_High_Order {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 9999);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .readTextFile("datas/input/OrderLog.csv")
                .map(line->{
                    String[] data = line.split(",");
                    return  new OrderEvent(Long.valueOf(data[0]), data[1], data[2], Long.valueOf(data[3]));
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((ele,ts)->ele.getEventTime())
                )
                .keyBy(OrderEvent::getOrderId)
                .window(EventTimeSessionWindows.withGap(Time.minutes(50)))
                .process(new ProcessWindowFunction<OrderEvent, String, Long, TimeWindow>() {

                    @Override
                    public void process(Long aLong,
                                        Context ctx,
                                        Iterable<OrderEvent> elements,
                                        Collector<String> out) throws Exception {

                        List<OrderEvent> list = AtguiguUtil.toList(elements);
                        if (list.size() == 2){
                            out.collect("订单 "+aLong+ " 正常交易");
                        }else{
                            OrderEvent orderEvent = list.get(0);
                            if (orderEvent.getEventType().equals("create")){
                                out.collect("订单 "+aLong+ " 只有create没有pay, 可能pay超时支付");
                            }else {
                                out.collect("订单 "+aLong+ " 只有pay没有create, 系统异常");
                            }
                        }

                    }
                }).print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
